import subprocess as sub


def default_worker(env):
    status = '404 NOT FOUND'
    headers = [('Content-Type', 'text/plain')]
    body = b'NOT FOUND'
    return status, headers, body


def cpu(env):
    p = sub.Popen(['uptime'], stdout=sub.PIPE)
    stdout = p.stdout.read().decode()
    p.wait()
    m1, m5, m15 = stdout.replace(',', '').split()[-3:]
    body = '1 minute: %s\n5 minutes: %s\n15 minutes: %s\n' % (m1, m5, m15)
    body = body.encode()
    status = '200 OK'
    headers = [
        ('Content-Type', 'text/plain'),
        ('Content-Length', str(len(body)))
    ]
    return status, headers, body


def ram(env):
    p = sub.Popen(['free'], stdout=sub.PIPE)
    stdout = p.stdout.read().decode()
    total, used, free = stdout.splitlines()[1].split()[1:4]
    body = 'total: %s\nused: %s\nfree: %s\n' % (total, used, free)
    body = body.encode()
    status = '200 OK'
    headers = [
        ('Content-Type', 'text/plain'),
        ('Content-Length', str(len(body)))
    ]
    return status, headers, body


def hd(env):
    p = sub.Popen(['df', '-h'], stdout=sub.PIPE)
    stdout = p.stdout.read().decode()
    lines = stdout.splitlines()
    root_line = [line for line in lines if line.endswith('/')][0]
    dev, size, used, avail, pct = root_line.split()[:5]
    fmt = 'dev: %s\nsize: %s\nused: %s\navail: %s\npct: %s\n'
    body = fmt % (dev, size, used, avail, pct)
    body = body.encode()
    status = '200 OK'
    headers = [
        ('Content-Type', 'text/plain'),
        ('Content-Length', str(len(body)))
    ]
    return status, headers, body
